use std::io::{self, Write};
use meval; // 确保 Cargo.toml 中有 meval = "0.2"

fn main() {
    let mut index = 1;
    let mut last_output: Option<f64> = None;

    println!("🦀 Rust Scientific Calculator v0.1");

    loop {
        print!("\nIn [{}]: ", index);
        io::stdout().flush().unwrap();

        let mut input = String::new();
        if io::stdin().read_line(&mut input).is_err() {
            println!("Failed to read input.");
            continue;
        }

        let input = input.trim();

        if input.contains("%%") {
            println!("Error: '%%' is not allowed.");
            continue;
        }

        if input.contains("__IO_INDEX__") {
            println!("name '__IO_INDEX__' is reserved");
            continue;
        }

        let mut expr_str = input.to_string();
        if input.contains('%') {
            match last_output {
                Some(val) => {
                    expr_str = expr_str.replace("%", &val.to_string());
                }
                None => {
                    println!("No previous output");
                    continue;
                }
            }
        }

        match meval::eval_str(&expr_str) {
            Ok(result) => {
                println!("Out[{}]: {}", index, result);
                last_output = Some(result);
            }
            Err(e) => {
                println!("Syntax or evaluation error: {}", e);
            }
        }

        index += 1;
    }
}
